<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      class="search-form clearfix"
    >
      <el-form-item class="search-field fl" label=" ">
        <div class="content-label three required">数据表</div>
        <el-cascader
          :options="tableNameTreeList"
          clearable
          :props="{value: 'dictItemId',label: 'dictLabel', emitPath: false}"
          placeholder="请选择数据表"
          v-model="dictItemId"
          @change="handleTableNameChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item
        :key="index"
        v-for="(item, index) in searchList"
        class="search-field fl"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select-dict
          v-if="item.type==='select'"
          :dictType="item.dictType"
          :clearable="item.clearable"
          :placeholder="item.placeholder"
          v-model="queryParams[item.prop]"
          @dictChange="handleQuery"
        ></el-select-dict>
        <el-input
          v-if="item.type==='input'"
          :clearable="item.clearable"
          :placeholder="item.placeholder"
          v-model.trim="queryParams[item.prop]"
          @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <el-form-item class="search-field fl" label="删除时间" prop="beginTime">
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          @change="handleQuery"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item class="fr">
        <el-button plain @click="resetQuery">重 置</el-button>
        <el-button type="primary" @click="handleQuery">查 询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-wrap">
      <div class="table-control-box" v-show="tableHeaderList.length > 0">
        <el-button
          v-hasPermi="['recycleBin:restore']"
          type="primary"
          plain
          icon="el-icon-back"
          size="mini"
          :disabled="multiple"
          @click="handleBatchRestore"
          >还原</el-button
        >
        <el-button
          v-hasPermi="['recycleBin:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          >彻底删除</el-button
        >
      </div>
      <div v-show="tableHeaderList.length === 0">
        <el-result title="提示" subTitle="请先选择数据表">
          <template slot="icon">
            <div class="recycle-img-box">
              <el-image fit="contain" src="https://www.xiaobu.host/static/recycle-bin.jpeg"></el-image>
            </div>
          </template>
        </el-result>
      </div>
      <div class="table-box" v-show="tableHeaderList.length > 0">
        <el-table
          ref="recycleBinTable"
          :class="{'empty': list.length === 0}" 
          empty-text=" "
          v-loading="loading"
          :data="list"
          row-key="configId"
          @selection-change="handleSelectionChange"
          @row-click="clickRow"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
            align="center"
          />
          <el-table-column-dict
            v-for="(item, index) in tableHeaderList"
            :key="index"
            :label="item.label || ''"
            :prop="item.prop || ''"
            :align="item.align || 'left'"
            :width="item.width || ''"
            :minWidth="item.minWidth || ''"
            :dictType="item.dictType || ''"
            :dictTypeNode="item.dictTypeNode || ''"
            :dateFormat="item.dateFormat || ''"
            :showOverflowTooltip="item.showOverflowTooltip || false"
          />
          <el-table-column-dict
            defaultVal="--"
            label="删除时间"
            align="center"
            width="168px"
            prop="updateTime"
          ></el-table-column-dict>
          <el-table-column
            v-if="hasPermi(['recycleBin:restore', 'recycleBin:delete'])"
            label="操作"
            align="center"
            width="256px"
            fixed="right"
            class-name="small-padding "
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['recycleBin:restore']"
                size="mini"
                type="primary"
                icon="el-icon-back"
                @click.native.stop="handleBatchRestore(scope.row)"
                >还原</el-button
              >
              <el-button
                v-hasPermi="['recycleBin:delete']"
                :disabled="scope.row.isSystem === '1'"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click.native.stop="handleBatchDelete(scope.row)"
                >彻底删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { recycleBinApi } from "@/api"
import { getDictObjByDictTypes } from "vue2-element-dict"
import {listArrToTreeArr, getPathByTreeValue, filterTreeArr} from "vue2-element-admin-plugin"
export default {
  name: "recycleBinManage",
  data() {
    return {
      dictItemId: "",
      //搜索条件参数
      queryParams: {
        tableName: "", // 表明
        beginTime: "", // 开始时间
        endTime: "", // 结束时间
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      list: [],
      selection: [], //选中的项
      loading: false,
      total: 0,
      roleList: [],

      // 非单个禁用
      single: true,
      // 非多个禁用(0个禁用)
      multiple: true,

      routerName: "", // 表对应的页面名 用户还原时 清除该页面的缓存 
      tableNameTreeList: [], // 数据库表 树形数据 字典数据
      tableHeaderList: [], // 表单列表
      searchList: [], // 搜索条件列表
      idField: "" // 删除的id字段名
    }
  },
  async created() {
    // 获取 TABLE 字典数据
    const data = await getDictObjByDictTypes("SQL_TABLE")
    const treeSetting = {
      firstId: null,
      idField: "dictItemId",
      labelField: "dictLabel",
      parentIdField: "parentDictItemId"
    }
    const treeList = listArrToTreeArr(data["SQL_TABLE"], treeSetting)
    this.tableNameTreeList = filterTreeArr(treeList, (item) => {
      // 叶子节点 且 没权限的 过滤掉
      return item.leaf && !this.$store.getters.sqlTableList.includes(item.dictValue)
    })
  },
  methods: {
    // 搜索表改变事件
    handleTableNameChange(val) {
      this.dateRange = []
      this.queryParams = {
        tableName: "", // 表明
        beginTime: "", // 开始时间
        endTime: "", // 结束时间
        pageNum: 1,
        pageSize: 10
      }
      if (!val) {
        this.routerName = ""
        this.tableHeaderList = []
        this.idField = ""
        this.searchList = []
        this.list = []
        this.total = 0
        return
      }
      const target = getPathByTreeValue(this.tableNameTreeList, val, {targetField: "dictItemId"})
      if (!target || target.length === 0) {
        this.$modal.msgError("未找到该表信息")
        return
      }
      const resultTarget = target[target.length - 1]
      this.queryParams.tableName = resultTarget.dictValue
      this.routerName = resultTarget.routerName || ""
      this.tableHeaderList = resultTarget.tableHeaderList || []
      this.idField = resultTarget.idField || ""
      this.searchList = resultTarget.searchList || []
      this.handleQuery()
    },
    //点击行
    clickRow(row) {
      this.$refs.recycleBinTable.toggleRowSelection(row)
    },
    //批量删除
    handleBatchDelete(data) {
      const _this = this
      const ids = data[this.idField]
        ? [data[this.idField]]
        : this.selection.map((item) => {
          return item[this.idField]
        })

      this.$modal
        .confirm("是否确认彻底删除已选中的" + ids.length + "项数据？")
        .then(function() {
          return recycleBinApi.batchDelete({
            ids,
            idField: _this.idField,
            tableName: _this.queryParams.tableName
          })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess("彻底删除数据成功")
        })
        .catch(() => {})
    },
    //批量还原
    handleBatchRestore(data) {
      const _this = this
      const ids = data[this.idField]
        ? [data[this.idField]]
        : this.selection.map((item) => {
          return item[this.idField]
        })

      this.$modal
        .confirm("是否确认还原已选中的" + ids.length + "项数据？")
        .then(function() {
          return recycleBinApi.batchRestore({
            ids,
            idField: _this.idField,
            tableName: _this.queryParams.tableName
          })
        })
        .then(() => {
          this.handleQuery()
          if (this.routerName) {
            // 还原成功时 清除掉  对应页面的缓存
            this.$store.commit("tagsView/DEL_CACHED_VIEW_BY_NAME", this.routerName)
          }
          this.$modal.msgSuccess("还原数据成功")
        })
        .catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.queryParams.tableName) {
        this.$modal.msgError("请选择数据表")
        return
      }
      // 清空已选项
      this.$refs.recycleBinTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.list = []
      this.total = 0
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      recycleBinApi
        .getRecycleBinList(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 编辑按钮操作 */
    handleRestore(row) {}
  }
}
</script>
<style lang="scss" scoped>
.recycle-img-box {
  width: 128px;
}
</style>